import { Drawer } from 'antd';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { getProjectDetailApi } from '@/pages/api/pro';

// echart相关的, 当window尺寸变化去重新调整图表尺寸
export const useEchartResize = (instance) => {
  useEffect(() => {
    const handleEchartResize = () => {
      instance.resize();
    };
    window.addEventListener('resize', handleEchartResize);
    return () => {
      window.removeEventListener('resize', handleEchartResize);
    };
  }, [instance]);
};

// 详情抽屉hook
export const useDetailDrawer = () => {
  const [detailVisible, setDetailVisible] = useState(false);
  const [detail, setDetail] = useState(null);

  const handleCheckItem = useCallback(async ({ proid }) => {
    setDetailVisible(true);
    setDetail(null);
    // 获取数据展示
    try {
      const proDetail = await getProjectDetailApi(proid);
      setDetail(proDetail);
    } catch (error) {
      console.log(error);
    }
  }, []);

  const drawer = useMemo(
    () => (
      <Drawer
        title="商品详情"
        placement="right"
        onClose={() => setDetailVisible(false)}
        visible={detailVisible}
      >
        <pre>{detail && JSON.stringify(detail, null, 2)}</pre>
      </Drawer>
    ),
    [detailVisible, detail],
  );

  return {
    drawer,
    check: handleCheckItem,
  };
};
